<?php

App::uses('Crud', 'Model');
App::uses('Test', 'Model');
App::uses('UserArea', 'Model');
App::uses('UserLine', 'Model');
App::uses('UserTest', 'Model');
App::uses('Area', 'Model');
App::uses('Room', 'Model');
App::uses('Moe', 'Model');
App::uses('Inscription', 'Model');
App::uses('Categorization', 'Model');

class Schedule extends Crud
{
    /** Al Agregar/eliminar/actualizar las constantes de los modelos implica ir
     * y actualizar los comentarios en los campos de la tabla asociada a este modelo.
     */
    const STATUS_ENABLED = 1;
    const STATUS_DISABLED = 0;
    const NO_CLOSED = 0;
    const CLOSED = 1;

    /**
     * Obtenemos los registros habilitados para el grid del admin
     * @param string $testId UUID Si este parametro no se define no se filtran
     * por examen. SI su valor es un id de un examen solo se muestran las programacion
     * para ese tipo de examen.
     * @return type
     */
    public function getEnabled($testId) {
        $filters = array(
            'fields' => array(
                'id',
                'user_id',
                'test_id',
                'description',
                'start_timezone',
                'start as test_date',
                'end',
                'end_timezone',
                'recurrence_rule',
                'recurrence_id',
                'recurrence_exception',
                'is_all_day',
                'r.name as location',
            ),
            'joins' => array(
                array(
                    'table' => 'us3rs_r4gg14n4',
                    'type' => 'INNER',
                    'alias' => 'u',
                    'conditions' => array(
                        'u.id = Schedule.user_id'
                    )
                ),
                array(
                    'table' => 'rooms',
                    'type' => 'INNER',
                    'alias' => 'r',
                    'conditions' => array(
                        'r.id = Schedule.room_id',
                    )
                ),
            ),
            'conditions' => array(
                'Schedule.status' => self::STATUS_ENABLED,
            ),
            'order' => array(
                'test_date' => 'DESC',
            ),
        );
        if ($testId !== null) {
            $filters['conditions']['test_id'] = $testId;
        }
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    /**
     * Obtenemos los examenes que puede presentar un usuario según su area
     * @param string $areaId UUID
     * @param string $userId UUID
     */
    public function getSchedulesByAreaIdAndUserId($areaId, $userId) {
        $filters = array(
            'fields' => array(
                'Schedule.id',
                't.name as testName',
                'start as test_date',
                'r.name as location',
            ),
            'joins' => array(
                array(
                    'table' => 'tests',
                    'type' => 'INNER',
                    'alias' => 't',
                    'conditions' => array(
                        't.id = Schedule.test_id',
                        't.status' => Test::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'rooms',
                    'type' => 'INNER',
                    'alias' => 'r',
                    'conditions' => array(
                        'r.id = Schedule.room_id',
                    )
                ),
                array(
                    'table' => 'inscriptions',
                    'type' => 'LEFT',
                    'alias' => 'i',
                    'conditions' => array(
                        'i.schedule_id = Schedule.id',
                        'i.user_id' => $userId,
                        'i.status' => Inscription::STATUS_ENABLED,
                    )
                ),
            ),
            'conditions' => array(
                'Schedule.status' => self::STATUS_ENABLED,
                't.area_id' => $areaId,
                'i.id IS NULL'
            ),
            'order' => array(
                'Schedule.start' => 'DESC',
            ),
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }
    
    public function getSchedulesByAreaIdAndUserId2($areaId, $userId) {
        $filters = array(
            'fields' => array(
                'i.id',
                't.name as testName',
                'start as test_date',
                'r.name as location',
            ),
            'joins' => array(
                array(
                    'table' => 'tests',
                    'type' => 'INNER',
                    'alias' => 't',
                    'conditions' => array(
                        't.id = Schedule.test_id',
                        't.status' => Test::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'rooms',
                    'type' => 'INNER',
                    'alias' => 'r',
                    'conditions' => array(
                        'r.id = Schedule.room_id',
                    )
                ),
                array(
                    'table' => 'inscriptions',
                    'type' => 'LEFT',
                    'alias' => 'i',
                    'conditions' => array(
                        'i.schedule_id = Schedule.id',
                        'i.user_id' => $userId,
                        'i.status' => Inscription::STATUS_ENABLED,
                    )
                ),
            ),
            'conditions' => array(
                'Schedule.status' => self::STATUS_ENABLED,
                't.area_id' => $areaId,
                'i.id IS NOT NULL'
            ),
            'order' => array(
                'Schedule.start' => 'DESC',
            ),
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }
    
    public function getByOwner($userId) {
        $filters = array(
            'fields' => array(
                'id',
                'user_id',
                'test_id',
                'room_id',
                'title',
                'description',
                'start_timezone',
                'DATE_FORMAT(start, "%Y-%m-%dT%TZ") as start',
                'DATE_FORMAT(end, "%Y-%m-%dT%TZ") as end',
                'end_timezone',
                'recurrence_rule',
                'recurrence_id',
                'recurrence_exception',
                'is_all_day',
                'color'
            ),
            'conditions' => array(
                'Schedule.status' => self::STATUS_ENABLED,
                'Schedule.user_id' => $userId
            )
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    public function getEnabledByArea($areaId) {
        $filters = array(
            'fields' => array(
                'Schedule.id as value',
                't.name as text',
            ),
            'joins' => array(
                array(
                    'table' => 'tests',
                    'type' => 'INNER',
                    'alias' => 't',
                    'conditions' => array(
                        't.id = Schedule.test_id',
                        't.area_id' => $areaId,
                        't.status' => Test::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'areas',
                    'type' => 'INNER',
                    'alias' => 'a',
                    'conditions' => array(
                        'a.id' => $areaId,
                        'a.status' => Area::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'moes',
                    'type' => 'INNER',
                    'alias' => 'm',
                    'conditions' => array(
                        'm.id = a.moe_id',
                        'm.status' => Moe::STATUS_ENABLED,
                    )
                )
            ),
            'conditions' => array(
                'Schedule.status' => self::STATUS_ENABLED,
            )
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    public function getTestInfo($scheduleId) {
        $filters = array(
            'fields' => array(
                't.id as value',
                't.minimum_qualification as min_cal',
                't.name as text',
                't.attempts as attempts',
                'r.name as room',
                'Schedule.start as start',
                'Schedule.room_capacity as capacity',
                'Schedule.users_registered as registered',
                'Schedule.closed as closed'
            ),
            'joins' => array(
                array(
                    'table' => 'tests',
                    'type' => 'INNER',
                    'alias' => 't',
                    'conditions' => array(
                        't.id = Schedule.test_id',
                        't.status' => Test::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'rooms',
                    'type' => 'INNER',
                    'alias' => 'r',
                    'conditions' => array(
                        'r.id = Schedule.room_id',
                        'r.status' => Room::STATUS_ENABLED
                    )
                )
            ),
            'conditions' => array(
                'Schedule.id' => $scheduleId,
                'Schedule.status' => self::STATUS_ENABLED,
            )
        );
        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }

    public function getTestByDates($startD, $endD, $filterClosed) {
        $filters = array(
            'fields' => array(
                'Schedule.id as value',
                't.name as text',
                'r.name as room',
                'Schedule.start as start',
                'Schedule.room_capacity as capacity',
                'Schedule.users_registered as registered',
                'Schedule.closed as closed',
                't.minimum_qualification as min_cal',
                't.attempts as attempts',
                't.id as train'
            ),
            'joins' => array(
                array(
                    'table' => 'rooms',
                    'type' => 'INNER',
                    'alias' => 'r',
                    'conditions' => array(
                        'r.id = Schedule.room_id',
                        'r.status' => Room::STATUS_ENABLED,
                    )
                ),
                array(
                    'table' => 'tests',
                    'type' => 'INNER',
                    'alias' => 't',
                    'conditions' => array(
                        't.id = Schedule.test_id',
                        't.status' => Test::STATUS_ENABLED,
                    )
                )
            ),
            'order' => array('start ASC'),
            'conditions' => array(
                'DATE(Schedule.start) >= DATE("' . $startD . '")',
                'DATE(Schedule.start) <= DATE("' . $endD . '")',
                'Schedule.status' => self::STATUS_ENABLED,
            )
        );
        if ($filterClosed == 'false') {
            $filters['conditions']['Schedule.closed'] = 0;
        }

        $records = $this->find('all', $filters);
        return $this->flatArray($records);
    }
}
